package cpcn.dsp.demo;

import com.alibaba.fastjson.JSONObject;
import cpcn.dsp.demo.api.query.CompanyVerifyQuery;
import cpcn.dsp.demo.consts.DSPConsts;
import cpcn.dsp.demo.util.HttpsUtil;
import cpcn.dsp.institution.api.security.EncryptAndDecrypt;
import cpcn.dsp.institution.api.system.DSPInstitutionEnvironment;
import cpcn.dsp.institution.api.tx.corpquery.Tx1304Request;
import cpcn.dsp.institution.api.tx.corpquery.Tx1304Response;
import cpcn.dsp.institution.api.util.Base64;
import cpcn.dsp.institution.api.util.GUIDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 工商认证服务
 */
@Slf4j
@Component
public class CpcnService {

    static {
        //初始化证书
        try {
            DSPInstitutionEnvironment.initialize(DSPConsts.Keystore_test, DSPConsts.myKeystorePassword_test, DSPConsts.publicKey_test, DSPConsts.MSG_ENCRYPT_20);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 工商四要素验证
     *
     * @param query
     * @throws Exception
     */
    public JSONObject companyVerify(CompanyVerifyQuery query) throws Exception {

        //生成请求明文
        Tx1304Request tx1304Request = new Tx1304Request();

        tx1304Request.setInstitutionID(DSPConsts.INSTITUTION_ID);// 机构号由中金分配
        tx1304Request.setTxSN(GUIDGenerator.genGUID());
        tx1304Request.setOrgIdentificationType(query.getOrgIdentificationType());
        tx1304Request.setOrganizationName(query.getOrganizationName());
        tx1304Request.setOrgIdentificationNumber(query.getOrgIdentificationNumber());
        tx1304Request.setName(query.getName());
        tx1304Request.setIdentificationType(query.getIdentificationType());
        tx1304Request.setIdentificationNumber(query.getIdentificationNumber());
        tx1304Request.setRemark(query.getRemark());//仅测试环境判断该字段1->不一致,2->未知，3->请求失败，其他->一致

        //报文处理
        tx1304Request.process();
        String plainText = tx1304Request.getRequestPlainText();
        log.info("请求明文{}", plainText);

        String reqMessage = tx1304Request.getRequestMessage();
        String reqSignature = tx1304Request.getRequestSignature();
        String requestDgtlEnvlp = tx1304Request.getRequestDgtlEnvlp();
        String requestSignSN = tx1304Request.getRequestSignSN();
        String requestEncryptSN = tx1304Request.getRequestEncryptSN();
        //生成参数
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("message", reqMessage);
        paramMap.put("signature", reqSignature);
        paramMap.put("dgtlenvlp", requestDgtlEnvlp);
        paramMap.put("signSN", requestSignSN);
        paramMap.put("encryptSN", requestEncryptSN);
        //生成请求参数
        String requestString = EncryptAndDecrypt.createLinkStringByGet(paramMap);
        log.info("请求密文：" + requestString);

        //请求接口
        String result = HttpsUtil.post(DSPConsts.TX_URL_TEST, requestString, null);
        log.info("响应密文：" + result);
        String respPlainText = null;
        String[] respMsg = result.split(",");
        if (respMsg.length == 1 && -1 == respMsg[0].indexOf(',')) {
            respPlainText = Base64.decode(respMsg[0], "UTF-8");
        } else if (respMsg.length == 5) {
            String responseMessage = respMsg[0];
            String responseSignature = respMsg[1];
            String responseDgtlEnvlp = respMsg[2];
            String respSignSN = respMsg[3];
            String respEncryptSN = respMsg[4];
            Tx1304Response tx1304Response = new Tx1304Response(responseMessage, responseSignature, responseDgtlEnvlp, respSignSN, respEncryptSN);
            respPlainText = tx1304Response.getResponsePlainText();
        }
        log.info("响应明文：" + respPlainText);
        return JSONObject.parseObject(respPlainText);
    }
}
